package com.antdesignbackend.backend.form.animalApplication.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.*;

import com.antdesignbackend.backend.activiti.constant.Constants;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.form.animalDaily.entity.AnimalDaily;
import com.antdesignbackend.backend.form.saleDeclarationA.entity.SaleDeclarationA;
import com.antdesignbackend.backend.form.saleDeclarationA.entity.entityVo.SaleDeclarationAVo;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.form.animalApplication.entity.AnimalApplication;
import com.antdesignbackend.backend.form.animalApplication.entity.entityVo.AnimalApplicationVo;
import com.antdesignbackend.backend.form.animalApplication.service.AnimalApplicationService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 出具《福建省动物、动物产品准调证》申请单
 *
 * @author 林宇杰
 * @email animalApplication
 * @date 2020-08-12 17:47:49
 */

@Controller
@RequestMapping("/animalApplication")
@Slf4j
public class AnimalApplicationController extends BaseController{

	private static final String FUN_NAME = "出具《福建省动物、动物产品准调证》申请单";//功能名称

	@Autowired
	private AnimalApplicationService animalApplicationService;

	@GetMapping("/index")
	@AuthToken
	public String index() {
		return "form/animalApplication/index";
	}

	/**
	 * 审批
	 * @return
	 */
	@GetMapping("/approval")
	@AuthToken
	public String approval() {
		return "form/animalApplication/approval";
	}


	@PostMapping("/tableSearch")
	@ResponseBody
	ReturnVO tableSearch(@RequestBody AnimalApplicationVo animalApplicationVo) throws SecurityException, IllegalArgumentException{
		ReturnVO result=new ReturnVO();
		List<AnimalApplication> animalApplications=new ArrayList<>();
		QueryWrapper<AnimalApplication> wrapper =new QueryWrapper<>();
		System.out.println("时间区间为"+animalApplicationVo.getTimeInterval());
		if (animalApplicationVo.getTypes() != null){
			wrapper.eq("types",animalApplicationVo.getTypes());
		}
		if (animalApplicationVo.getTimeInterval() != null && !animalApplicationVo.getTimeInterval().equals("")){
			String[] str=animalApplicationVo.getTimeInterval().split(" - ");
			String star=str[0];
			String end=str[1];
			wrapper.between("applicationDate",star,end);
		}
		if ("2".equals(getUserType())){

		}else if ("3".equals(getUserType())){
			wrapper.eq("eid",getLoginEnterpriseId());
		}else {
			wrapper.eq("eid",0);
		}
		wrapper.orderByDesc("applicationDate");
		//先统计满足条件的数据总数，因为sql 不包括排序
		int total=animalApplicationService.count(wrapper);
		result.setTotal(total);
		System.out.println("*******************************满足条件的数据有："+total);
		//再查询
		if(total>=0)
		{
			animalApplications=animalApplicationService.page(new Page<AnimalApplication>(animalApplicationVo.getPageIndex(),animalApplicationVo.getPageSize()),wrapper).getRecords();
			for(AnimalApplication animalApplication:animalApplications){
				if(!animalApplication.getLicensePhoto().equals("")){
					animalApplication.setLicensePhoto(WebConfig.host+"images/"+animalApplication.getLicensePhoto());
				}
				if(!animalApplication.getReportPhoto().equals("")){
					animalApplication.setReportPhoto(WebConfig.host+"images/"+animalApplication.getReportPhoto());
				}
			}
		}
		result.setData(animalApplications);
		return result;
	}

	@GetMapping("/getById/{id}")
	@ResponseBody
	public	AnimalApplication getById(@PathVariable(name = "id") String id) {
		AnimalApplication obj = animalApplicationService.getById(id);
		return obj;
	}

	@PostMapping("/save")
	@ResponseBody
	public ReturnVO save(@RequestBody AnimalApplication animalApplication){
		ReturnVO result = new ReturnVO();
		animalApplication.setTypes(0);//审批中
		animalApplication.setCreateBy(getLoginUserId());
		animalApplication.setCreateTime(new Date());
		animalApplication.setEid(getLoginEnterpriseId());
		try {
			animalApplicationService.save(animalApplication);
		}catch (Exception e){
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	@PostMapping("update")
	@ResponseBody
	public ReturnVO updateById(@RequestBody AnimalApplication animalApplication){
		ReturnVO result = new ReturnVO();
		animalApplication.setTypes(0);//审批中
		animalApplication.setCreateBy(getLoginUserId());
		animalApplication.setCreateTime(new Date());
		animalApplication.setEid(getLoginEnterpriseId());
		try {
			animalApplicationService.updateById(animalApplication);
		}catch (Exception e){
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	/**
     * 根据id删除
     */
	@DeleteMapping("/deleteById/{id}")
	@ResponseBody
	public ReturnVO deleteById(@PathVariable Serializable id) {
		ReturnVO result = new ReturnVO();
		if (animalApplicationService.removeById(Integer.parseInt(id.toString())) == true) {
			result.setMessage("删除成功");
		} else {
			result.setMessage("删除失败");
			result.setCode("0");
		}
		return result;
	}
	/***
	 * 上传图片
	 * @return
	 */
	@PostMapping("/uploadImages")
	@ResponseBody
	public Map<String,String> uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8") ;
		long random =System.currentTimeMillis();
		String dateKey =random+"";
		String localPathDir="";
		String newFileName="";
		Map<String,String> map = new HashMap<>();
		if(!WebConfig.uploadImage.equals(""))
		{
			localPathDir=WebConfig.uploadImage;
		}
		else
		{
			localPathDir= ResourceUtils.getURL("classpath:").getPath()+"images/";
		}
		File logoSaveFile = new File(localPathDir);
		if(!logoSaveFile.exists()){
			logoSaveFile.mkdirs();
		}
		if (request instanceof MultipartHttpServletRequest) {
			MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
			Iterator iter = mr.getFileMap().values().iterator();
			if (iter.hasNext()) {
				MultipartFile file = (MultipartFile) iter.next();
				String oname = file.getOriginalFilename();
				String fileTyle=oname.substring(oname.lastIndexOf("."),oname.length());
				fileTyle=fileTyle.toLowerCase();
				newFileName=dateKey+fileTyle;
				String fileName = localPathDir+newFileName;
				if(fileTyle.equals(".png") || fileTyle.equals(".gif") || fileTyle.equals(".jpg"))
				{
					File files = new File(fileName);
					InputStream inputstream =file.getInputStream();
					byte[] bytes = new byte[1024];
					FileOutputStream outstream = new FileOutputStream(fileName);
					int index;
					while ((index = inputstream.read(bytes)) != -1) {
						outstream.write(bytes, 0, index);
						outstream.flush();
					}
					outstream.close();
					inputstream.close();
				}
			}
		}
		if(newFileName!=null && !newFileName.equals(""))
		{
			map.put("url",newFileName);
			map.put("httpUrl",WebConfig.host+"images/"+newFileName);
		}
		// System.out.println("return:"+localPathDir+newFileName);
		return map;
	}

	/**
	 * 审批
	 * @param vo
	 * @return
	 */
	@PostMapping("/action")
	@ResponseBody
	public ReturnVO action(@RequestBody AnimalApplicationVo vo) {
		ReturnVO result = new ReturnVO();
		Boolean b = false;
		try {
			switch (vo.getAction()){
				case "aproval": //审批
					AnimalApplication animalApplication = new AnimalApplication();
					animalApplication.setId(vo.getId());
					animalApplication.setTypes(vo.getTypes());
					animalApplication.setOpinion(vo.getOpinion());
					animalApplication.setAprovalTime(new Date());
					animalApplication.setAprovalId(getLoginUserId());
					animalApplication.setAproval(getLoginUserName());
					b = animalApplicationService.updateById(animalApplication);
					break;
				case "certificate": //出证
					AnimalApplication animalApplication1 = new AnimalApplication();
					animalApplication1.setId(vo.getId());
					animalApplication1.setTypes(3);
					animalApplication1.setCertificateId(getLoginUserId());
					animalApplication1.setCertificate(getLoginUserName());
					animalApplication1.setWitness(vo.getWitness());
					animalApplication1.setLivestock(vo.getLivestock());
					animalApplication1.setCertificateTime(new Date());
					b = animalApplicationService.updateById(animalApplication1);
					break;
			}
		}catch (Exception e){
			b = false;
		}
		if (!b){
			result.setMessage("操作失败！");
			result.setCode("500");
		}
		return result;
	}

}
